package quiz;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowQuizzesServlet
 */
@WebServlet("/ShowQuizzes")
public class ShowQuizzesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowQuizzesServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		
		int userID = Account.ANONYMOUS_ACCOUNT_ID;
		
		if (request.getSession().getAttribute("account") != null)
				userID = ((Account)request.getSession().getAttribute("account")).getID();
		
		ArrayList<String> tags = db.getPopularTags(12);
		ArrayList<Quiz> recent = db.getRecentlyCreatedQuizzes(userID, 12);
		ArrayList<Quiz> popular = db.getPopularQuizzes(userID, 12);
		
		if (recent == null) recent = new ArrayList<Quiz>();
		if (popular == null) recent = new ArrayList<Quiz>();
		
		request.setAttribute("popularTags", tags);
		request.setAttribute("recentQuizzes", recent);
		request.setAttribute("popularQuizzes", popular); //empty if no quizzes
				
		RequestDispatcher dpatch = request.getRequestDispatcher("take-quiz.jsp");
		dpatch.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("ShowQuizzes");
	}

}
